#include "../include/dir.h"

int handle_cd(path_t *path, const char* destDir, char *buf, int buf_len){
    
    ////存放未规范前新虚拟路径
    //char newVirPath[MAX_PATH_LEN] = {0}; 
    
    ////判断绝对 相对路径
    //if(destDir[0] == '/'){
    //    //绝对路径
    //    sprintf(newVirPath, "%s", destDir);
    //}
    //else{
    //    //相对路径
    //    if(strcmp(path->virtualPath, "/") == 0){
    //        //在虚拟根目录
    //        sprintf(newVirPath, "/%s", destDir);
    //    }
    //    else{
    //        sprintf(newVirPath, "%s/%s", path->virtualPath, destDir);
    //    }
    //}

    ////规范路径 并执行入栈出栈
    //char stack[50][MAX_PATH_LEN] = {0}; //栈存放目录名
    //int top = 0;
    //char *token;
    //char *saveptr; //strtok_r所需的维护指针
    //token = strtok_r(newVirPath, "/", &saveptr); 
    //while(token){
    //    if(strcmp(token, ".") == 0){} //无视
    //    else if(strcmp(token, "..") == 0){
    //        //虚拟根目录则无视
    //        if(top > 0){
    //            top--;
    //        }
    //    }
    //    else{
    //        strncpy(stack[top], token, MAX_PATH_LEN-1);
    //        top++;
    //    }
    //    token = strtok_r(NULL, "/", &saveptr);
    //}    

    ////出栈->拿到规范后的新虚拟路径
    //bzero(newVirPath, sizeof(newVirPath));
    //for(int i = 0; i < top; i++){
    //    int len = sizeof(newVirPath)-strlen(newVirPath)-1;
    //    strncat(newVirPath, "/", len);
    //    strncat(newVirPath, stack[i], len);
    //}
    //
    ////如果destDir是.或.. 被无视 空栈则虚拟还是/
    //if(strlen(newVirPath) == 0){
    //    strncpy(newVirPath, "/", sizeof(newVirPath));
    //}
    //
    ////已拿到规范虚拟地址->拼接出真实->检查是否存在->检查是否为目录
    ////拼接真实
    //char newRealPath[MAX_PATH_LEN] = {0};
    //strncpy(newRealPath, path->initPath, sizeof(newRealPath));//初始化
    //strncat(newRealPath, newVirPath, sizeof(newRealPath)-strlen(newRealPath)-1);
    
    //清空buf 避免调用了多次带buf的函数后面会输出前面buf内容 测试问题mkdir->ls
    bzero(buf, buf_len);
    
    //存放未规范前新虚拟路径
    char newVirPath[MAX_PATH_LEN] = {0}; 
    char newRealPath[MAX_PATH_LEN] = {0};

    //获取规范路径
    makePath(path, destDir, newVirPath, newRealPath);

    //检查是否存在 F_OK存在 X_OK执行(目录打开权限) 
    if(access(newRealPath, F_OK) != 0){
        strncpy(buf, "请输入正确路径.\n", buf_len-1);
        return -1;
    }
    else if(access(newRealPath, X_OK) != 0){
        strncpy(buf, "无打开权限.\n", buf_len-1);
        return -1;
    }

    ////有打开权限->检查是否为目录
    //DIR *dirp = opendir(newRealPath);
    //if(dirp){
    //    closedir(dirp);
    //}
    //else{
    //    strncpy(buf, "不是目录.\n", buf_len-1);
    //    return -1;
    //}
    struct stat st;
    stat(newRealPath, &st);
    if(!S_ISDIR(st.st_mode)){
        strncpy(buf, "不是目录.\n", buf_len-1);
        return -1;
    }
    
    //一切安好->更新path
    strncpy(path->realPath, newRealPath, MAX_PATH_LEN);
    strncpy(path->virtualPath, newVirPath, MAX_PATH_LEN);

    return 0;
}
